//
//  AddFeedViewController.m
//  Feed Rider
//
//  Created by Adrian-Sergiu Nicuta on 23/09/11.
//  Copyright 2011 Adrisen Technologies SPRL. All rights reserved.
//

#import "AddFeedViewController.h"

@implementation AddFeedViewController

@synthesize FeedTitle;
@synthesize FeedURL;
@synthesize FeedCategory;
@synthesize fetchedResultsController = __fetchedResultsController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"Add RSS feed";
    
    // Do any additional setup after loading the view from its nib.
    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveFeed:)];
    
    self.navigationItem.rightBarButtonItem = saveBtn;
    [saveBtn release];
}

- (void)viewDidUnload
{
    [self setFeedURL:nil];
    [self setFeedCategory:nil];
    [self setFeedTitle:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (IBAction)saveFeed:(id)sender {
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    Feed *newFeed = (Feed *)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

    newFeed.Title = FeedTitle.text;
    newFeed.url = FeedURL.text;
    newFeed.Category = FeedCategory.text;
    newFeed.unreadCount = [NSNumber numberWithInt:0];
    
    NSError *error = nil;
    
    if(![context save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [FeedURL release];
    [FeedCategory release];
    [FeedTitle release];
    [super dealloc];
}
@end
